package com.qingmeng.apigateway.filter;

import com.qingmeng.apiclientsdk.utils.SignUtils;
import com.qingmeng.apicommon.model.entity.InterfaceInfo;
import com.qingmeng.apicommon.model.entity.User;
import com.qingmeng.apicommon.model.entity.UserInterfaceInfo;
import com.qingmeng.apicommon.service.RemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private RemoteService remoteService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    /**
     * 全局过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、接收用户的API请求
        // 2、记录用户请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识：" + request.getId());
        RequestPath path = request.getPath();
        HttpMethod method = request.getMethod();
        log.info("请求路径：" + path);
        log.info("请求方法：" + method);
        log.info("请求参数：" + request.getQueryParams().toSingleValueMap());
        //请求来源地址
        InetSocketAddress localAddress = request.getLocalAddress();
        log.info("请求来源地址：" + localAddress);
        ServerHttpResponse response = exchange.getResponse();

        // 黑白名单（一般使用白名单，即只允许白名单之内的用户访问）
        if (!IP_WHITE_LIST.contains(localAddress.getHostName())) {
            handNoAuth(response);
        }

        // 3、判断用户权限（用户鉴权）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String body = headers.getFirst("body");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");

        //2、从数据库中查询accessKey，并判断是否有效
        User invokerUser = null;
       try {
           invokerUser = remoteService.getInvokerUser(accessKey);
       }catch (Exception e){
           return handNoAuth(response);
       }
        if (invokerUser == null){
            return handNoAuth(response);
        }

        //3、校验一下随机数 todo 随机数可以存储在redis中或者用hashmap存储，这里也应该查询而不是比较是否大于10000
        if (Long.parseLong(nonce) > 10000) {
            return handNoAuth(response);
        }

        //4、校验时间戳与当前时间的差距，todo 可以使用常量来保存时间
        Long currentTIme = System.currentTimeMillis() / 1000;
        final Long FIVE_MINUTES = 60 * 5L;
        if ((currentTIme - Long.parseLong(timestamp)) > FIVE_MINUTES) {
            return handNoAuth(response);
        }

        //5、校验签名是否正确
        //  这里的secretKey 上面根据ak查询到用户的所有信息
        String secretKey = invokerUser.getSecretKey();
        String serverSign = SignUtils.getSign(body, secretKey);
        if (!sign.equals(serverSign)) {
            return handNoAuth(response);
        }

        // 4、判断接口是否存在
        //从数据库中查询模拟接口是否存在，以及请求方法是否匹配（还可以校验请求参数）
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = remoteService.isInvokeMock(path.value(), method.name());
        }catch (Exception e){
            return handNoAuth(response);
        }
        if (interfaceInfo == null){
            return handNoAuth(response);
        }

        // 5、 判断用户是否还有调用次数
        try {
            boolean b = remoteService.invokeHaveNum(invokerUser.getId(), interfaceInfo.getId());
        }catch (Exception e){
            log.error("网关捕获异常：调用次数不足");
            return handNoHaveNum(response);
        }


        // 6、请求转发，调用模拟接口，并返回结果
        Mono<Void> filter = chain.filter(exchange);
        return handleResponse(exchange, chain, invokerUser.getId(), interfaceInfo.getId());
    }


    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,Long userId,Long interfaceInfoId) {
        try {
            // 获取原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 获取数据缓冲工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 获取响应的状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            // 判断状态码是否为200 OK(按道理来说,现在没有调用,是拿不到响应码的,对这个保持怀疑 沉思.jpg)
            if(statusCode == HttpStatus.OK) {
                // 创建一个装饰后的响应对象(开始穿装备，增强能力)
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 重写writeWith方法，用于处理响应体的数据
                    // 这段方法就是只要当我们的模拟接口调用完成之后,等它返回结果，
                    // 就会调用writeWith方法,我们就能根据响应结果做一些自己的处理
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        // 判断响应体是否是Flux类型
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 返回一个处理后的响应体
                            // (这里就理解为它在拼接字符串,它把缓冲区的数据取出来，一点一点拼接好)
                            return super.writeWith(fluxBody.map(dataBuffer -> {

                                //8、调用成功，用户接口调用次数+1 invokeCount
                                remoteService.invokeCountNum(userId,interfaceInfoId);

                                // 读取响应体的内容并转换为字节数组
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);// 将处理后的内容重新包装成DataBuffer并返回

                                //打印响应日志
                                log.info("响应结果：" + data);
                                //设置新的响应码为服务器异常
                                log.info("响应码: {}, 响应体: {}", statusCode, data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("响应code异常：", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 对于200 OK的请求,将装饰后的响应对象传递给下一个过滤器链,并继续处理(设置repsonse对象为装饰过的)
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            // 对于非200 OK的请求，直接返回，进行降级处理
            //9、todo 调用失败，返回一个规范 的错误码
            handError(exchange.getResponse());
            return chain.filter(exchange);
        }catch (Exception e){
            // 处理异常情况，记录错误日志
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    /**
     * 优先级
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 用户没有授权，设置响应
     * @param response
     * @return
     */
    public Mono<Void> handNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    /**
     * 用户没有调用次数
     */
    public Mono<Void> handNoHaveNum(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    /**
     * 调用失败，设置响应
     * @param response
     * @return
     */
    public Mono<Void> handError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
       return response.setComplete();
    }
}